<?php
namespace App\Models;
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/9/4
 * Time: 12:53
 */

class Recharge extends BaseModel{
    protected $table = "recharge";

    public function getOne($where, $fileds = '*', $order = '')
    {
        if (!$order) {
            $order = ['id' => 'desc'];
        }
        return $this->multiSelect($fileds)->multiWhere($where)->multiOrder($order)->first();
    }

    /**
     * 按条件查询全部数据,根据配置显示条数显示
     */
    public function getList(array $where = [], $fields = '*', $order = '', $pageSize = '')
    {
        if ($pageSize) {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->paginate($pageSize);
        } else {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->get();
        }
    }

    /**
     * 按条件查询全部数据,根据配置显示条数显示
     */
    public function getWithMemberList(array $where = [], $fields = '*', $order = '', $pageSize = '')
    {
        if ($pageSize) {
            return $this->with('member')->multiSelect($fields)->multiWhere($where)->multiOrder($order)->paginate($pageSize);
        } else {
            return $this->with('member')->multiSelect($fields)->multiWhere($where)->multiOrder($order)->get();
        }
    }

    public function member()
    {
        return $this->hasOne('App\Models\Member', 'id', 'member_id');
    }

    /**
     *插入数据
     */
    public function add($data)
    {
        return $this->_add($data);
    }


    /***
     * @param array $id
     * @param array $data
     * 更新数据
     */
    public function up($where, $data)
    {
        return $this->_updata($where, $data);
    }



    /**
     * @param $id
     * 删除数据
     */
    public function del($where)
    {
        return $this->_del($where);
    }


    /**
     * 添加充值订单
     * @param $request
     */
    public function addRechagr($request){
         // 判断 表单内容
         $eth = $request['money'];
         if(empty($eth)){
                $res['state'] = 400;
                $res['msg']   = '充币数量不能为空';
                return $res;
         }

         if(!is_numeric($eth)){
             $res['state'] = 400;
             $res['msg']   = '充币数量必须为数字';
             return $res;
         }

         if($eth<=0){
            $res['state'] = 400;
            $res['msg']   = '充币数量必须为数字';
            return $res;
         }

         $setting = new Setting();
         $system = $setting->getSetting('system');
         $data['order_sn'] = $this->makePaySn(session('uid'));
         $data['state']   = "请尽快转币并且发送截图到邮箱".$system['email'];
         $data['member_id'] = session('uid');
         $data['type']   = $request['type'];
         $data['ethurl'] = $request['ethurl'];
         $data['amount']  = $request['money'];
         $data['created_at'] = date("Y-m-d H:i:s",time());
         $data['updated_at'] = date("Y-m-d H:i:s",time());
         $reslute = $this->add($data);

         if($reslute){
             $res['state'] = 200;
             $res['msg']   = '充币数量成功';
         }else{
             $res['state'] = 400;
             $res['msg']   = '充币数量失败';
         }
         return $res;
    }

    /**
     * 读取充值记录
     */
    public function rechargeList(){
        $where['member_id'] = session('uid');
        $order['id'] = 'desc';
        $rows = $this->getList($where, '*', $order, 5);
        if ($rows) {
            $rows = $rows->toArray();
            $rows['pageNoList'] = $this->getPageNoList($rows['last_page'], request('page', 1), 10);
            return $rows;
        }

    }

    /**
     * 生成支付单编号(两位随机 + 从2000-01-01 00:00:00 到现在的秒数+微秒+会员ID%1000)，该值会传给第三方支付接口
     * 长度 =2位 + 10位 + 3位 + 3位  = 18位
     * 1000个会员同一微秒提订单，重复机率为1/100
     * @return string
     */
    public function makePaySn($member_id) {
        return mt_rand(10,99)
        . sprintf('%010d',time() - 946656000)
        . sprintf('%03d', (float) microtime() * 1000)
        . sprintf('%03d', (int) $member_id % 1000);
    }


    /**
     * 修改订单付款状态
     */
    public function changeOrderStatus($request){

        $id = $request['id'];     //获取订单id
        $where['id'] = $id;
        $rechargeinfo = $this->getOne($where);    //根据id获取该条订单详细信息

        if($rechargeinfo['actual_arrival']!=0){   //如果表中字段不为0,则说明已经到账,无法再次确认

            $ajaxData['status'] = 0;
            $ajaxData['msg'] = '已确认过,无法重复提交';
            return $ajaxData;

        }

        //开启事务处理
        $this->start();

        try{

        //①更新付款状态
        switch($rechargeinfo['type']){
            case 1:
            $coin_type = 'eth';      //教育币
            break;
            case 2:
            $coin_type = 'btc';      //比特币
            break;
            default:
            $coin_type = 'none';

        }

        $settingmodel = new Setting();  //实例化设置表模型,用于通过币种获取比例
        $res3 = $settingmodel->getOne(array('name'=>$coin_type));
        $bili = $res3['value'];         //得到该币种的比例

        $amount = $rechargeinfo['amount'];    //提交货币数量
        $data['actual_arrival'] = $amount;     //实际到账数量=提交货币数量
        $data['state'] = '到账成功!';
        $data['updated_at'] = date('Y-m-d H:i:s');
        $res = $this->up($where, $data);    //更新recharge表数据

        //②member表edu入库
        $membermodel = new Member();
        $where2['id'] = $rechargeinfo['member_id'];    //该订单的用户id
        $memberinfo = $membermodel->getOne($where2);   //取出用户信息
         if($coin_type=='eth'){
             $edu_amount = $memberinfo['edu_amount'] + $amount;     //如果是教育币直接入库
         }else{
             $edu_amount = $memberinfo['edu_amount'] + $amount*$bili;   //如果是比特币就转成教育币
         }

        $membermodel->up($where2, array('edu_amount'=>$edu_amount));   //导入用户个人账户

        //③充值日志
        $rechargeinfo2 = $this->getOne($where);    //更新后的该条订单详细信息
        $logmodel = new Log();   //实例化log模型用于调用addlog函数
        $logmodel->addLog($rechargeinfo2,1);  //1 充值  2 提现
        $this->commit();

        }catch (\Exception $e){
            $this->rollBack();
            //echo $e->getMessage();die();
            $ajaxData['status'] = 0;
            $ajaxData['msg'] = '确认到账失败!';
            return $ajaxData;
        }

        $ajaxData['status'] = 1;
        $ajaxData['msg'] = '确认到账成功!';
        return $ajaxData;

    }

    /**
     *
     * 获取充值订单列表,带分页
     *
     */
    public function getOrderList($request){
        $keyword = $request['keyword'] ? trim($request['keyword']) : '';
        $where = [];
        if ($keyword) {
            if (is_numeric($request['keywords'])) {
                $where['member_mobile'] = $request['keywords'];
            } else {
                $where['pet_name'] = ['like', '%' . $request['keywords'] . '%'];
            }
        }
        $start = date("Y-m-d",strtotime($request['starttime']));
        $end = date("Y-m-d",strtotime($request['endtime']));
        $start1 = $start;
        $end1 = $end;
        if($start>$end){
            $start1 = $end;
            $end1 = $start;
        }
        if($request['starttime']&&$request['endtime']){
            $where['updated_at'] = ['glt',[['>',$start1],['<=',$end1]]];;
        }

        $order['id'] = 'desc';

        $data = $this->getWithMemberList($where, '*', $order, 10);
        //dd($data);
        if ($data) {
            $data = $data->toArray();

            $data['pageNoList'] = $this->getPageNoList($data['last_page'], request('page', 1), 10);
        }
        //dd($data);
        return $data;
    }

}